package com.ambimmort.shj.service.generalfile;

import cn.net.greenet.common.db_service.BaseDao;
import cn.net.greenet.db.HibernateUtil;
import cn.net.greenet.generalfile.logic.GeneralFileProcess;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Service;

import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by 师梁 on 2015/7/30.
 */
@Service("readApp2UIService")
public class ReadApp2UIService {

    ResultSet rs = null;
    BaseDao baseDao = null;

    private void init() {
        baseDao = new BaseDao();
    }

    private void close() {
        if (baseDao != null) {
            baseDao.close();
        }
    }

    public String read(String pageCount, String page, String MessageType, String policy_instance, String iDisplayStart, String iDisplayLength) {

        JSONObject json = new JSONObject();
        JSONArray result = new JSONArray();
//            SessionFactory sf = HibernateUtil.getSessionFactory();
//            Session session = sf.openSession();
//            session.clear();
//            List li = session.createSQLQuery(sql).list();
//            session.close();
//            int length = li.size();

        init();
        String sql = GeneralFileProcess.QUERY_APP;
        rs = baseDao.executeSQL(sql, new Object[]{});
        int length = 0;
        try {
            length = rs.getRow();
            List li = new ArrayList();
            if (rs.next()) {
                li.add(rs);
            }
            json.put("iTotalRecords", length);
            json.put("iTotalDisplayRecords", length);
            int end = Integer.parseInt(iDisplayStart) + Integer.parseInt(iDisplayLength);
            if (end > length) {
                end = length;
            }
            for (int i = Integer.parseInt(iDisplayStart); i < end; i++) {
                Object[] oo = (Object[]) li.get(i);
                JSONArray one = new JSONArray();
                //name+AppType_id+appid
                String id = oo[1].toString() + "_" + oo[0].toString() + "_" + oo[3].toString();
                one.add(oo[1]);
                one.add(oo[2]);
                one.add(oo[3]);
                one.add("<a class='red' href='javascript:void(0)' title='删除' onclick='delectObj(" + id + ")'><i class='icon-trash bigger-130'></i></a>");
                result.add(one);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
        json.put("aaData", result);
        close();
        return json.toString();
    }
}
